/**
 * Created by zhangyida on 15/12/29.
 */
'use strict';

import {
    View,
    TouchableOpacity,
    Navigator,
    Text,
    Image,
    Modal,
    ListView,
    StyleSheet,
    SegmentedControlIOS,
    TouchableHighlight,
    AlertIOS,
    Animated,
    ScrollView,
    Easing,
    ActivityIndicator
} from 'react-native';
import React from 'react';
import URL from '../config/server';
import {Utils} from '../config/utils';
import {Key} from '../config/key';
import Footer from '../component/Footer';
import Icon from 'react-native-vector-icons/Ionicons';
import ScrollNews from '../component/ScrollNews';

//这里放公共的函数
function formatDate2(date) {
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}

function formateDate3(str) {
    str = str.replace(/-/g, "/");
    let date = new Date(str);
    return date;
}

function reformData(data) {
    //函数将原始数据进行分块;
    let dataBlob = {};
    let sectionIDs = [];
    let rowIDs = [];
    var rowSecId = [];
    let rowNum = [];
    let curSecNum = 0;
    let i = 0;
    let rowIndex = 0;

    //1.获取section数组
    data.forEach(function (ele) {
        let sectionId = ele.byzd1;
        let sectionData = ele.byzd1;
        if (sectionIDs.indexOf(sectionData) == -1) {
            sectionIDs.push(sectionData);
        }
    });


    //2.获取每个section的rows个数
    for (let k = 0; k < sectionIDs.length; k++) {

        //再遍历插入rows
        data.forEach(function (ele, index) {
            if (ele.byzd1 == sectionIDs[k]) {
                ++curSecNum;
            }
        });

        //rowsNum插入当前rows数
        rowNum.push(curSecNum);
        curSecNum = 0;
    }


    //获取rows数组
    for (let j = 0; j < sectionIDs.length; j++) {
        let curSec = sectionIDs[j];
        //先插入sectionID
        dataBlob[curSec] = sectionIDs[j];

        //再遍历插入rows
        for (let m = 0; m < rowNum[j]; m++) {
            let rowId = ' ' + data[rowIndex].id;

            dataBlob[rowId] = data[rowIndex];
            ++rowIndex;
            rowSecId.push(rowId);

        }

        //rows插入secid
        rowIDs.push(rowSecId);
        rowSecId = [];
    }

    return {
        _dataBlob: dataBlob,
        _sectionID: sectionIDs,
        _rowIDs: rowIDs
    };
}

function getSectionData(dataBlob, sectionID) {
    return dataBlob[sectionID];
}
function getRowData(dataBlob, sectionID, rowID) {
    return dataBlob[rowID];
}
var NcTimer;
var NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return (
            <TouchableOpacity
                style={{flex: 1, justifyContent: 'center',paddingLeft:10}}
                onPress={() => navigator.parentNavigator.pop()}>
                <View style={{flexDirection:'row',padding:5}}>
                    <Icon name="ios-arrow-back" size={18} color="#ffffff" style={{alignSelf:'center'}}/>
                    <Text style={{color: 'white', margin: 3,fontSize:18}}>
                        返回
                    </Text>
                </View>
            </TouchableOpacity>
        );
    },
    RightButton(route, navigator, index, navState) {
        return (
            <Search navigator={navigator}/>
        );
    },

    Title(route, navigator, index, navState) {
        console.log(navigator.props.message.ncType == 1);
        let Name = '';

        switch (navigator.props.message.ncType) {
            case 1:
                Name = '初级内参';
                break;
            case 2:
                Name = '个人内参';
                break;
            case 3:
                Name = '白金内参';
                break;
            case 4:
                Name = '私募内参';
                break;
            default:
                Name = '神秘内参'
        }
        return (
            <Text style={styles.navTitle}>
                {Name}
            </Text>
        );
    }
};

class Search extends React.Component {

    _toSeach() {
        clearInterval(NcTimer);
        this.props.navigator.parentNavigator.push({
            id: 'NcSearch',
            message: this.props.navigator.props.message,
            sceneConfig: Navigator.SceneConfigs.FloatFromBottom
        })
    }

    render() {
        return (
            <TouchableOpacity onPress={this._toSeach.bind(this)} underColor="#e02820" style={styles.search}>
                <Icon name="ios-search" size={26} color="#ffffff"/>
            </TouchableOpacity>
        );
    }
}
class ListHead extends React.Component {
    render() {
        return (
            <View style={styles.th}>
                <Text style={[styles.thText,{flex:3}]}>发布日期</Text>
                <Text style={[styles.thText,{flex:2}]}>股票代码</Text>
                <Text style={[styles.thText,{flex:2}]}>股票名称</Text>
                <Text style={[styles.thText,{flex:2}]}>买点</Text>
                <Text style={[styles.thText,{flex:2}]}>止损</Text>
                <Text style={[styles.thText,{flex:2}]}>止盈</Text>
                <Text style={[styles.thText,{flex:2}]}>持仓时间</Text>
                <Text style={[styles.thText,{flex:2}]}>评级</Text>
            </View>
        );
    }
}

export default class Nc extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modalVisiable: false,
            dataSource: new ListView.DataSource({
                getRowData: getRowData,
                getSectionHeaderData: getSectionData,
                rowHasChanged: (row1, row2) => row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2
            }),
            loaded: 0,
            loadMore: true,
            pagesize: 20,
            showDate: this.props.message.showDate == null ? new Date() : formateDate3(this.props.message.showDate),
            scroll: '',
            angle: new Animated.Value(0)
        };

    }

    componentDidMount() {
        console.log("第一次加载！！");
        this.fetchData();
        this.fetchScroll();
        NcTimer = setInterval(()=> {
            this.fetchData();
        }, 10000);
    }

    componentWillUnmount() {
        clearInterval(NcTimer);
    }

    fetchScroll() {
        let that = this;
        const SCROLL = URL.local + 'roll';
        Utils.get(SCROLL, function (data) {
            that.setState({
                scroll: data.content
            })
        })
    }

    triggerModal() {

        this.setState({
            modalVisiable: true
        });
        let setTimer = setTimeout(()=> {
            this.setState({
                modalVisiable: false
            })
        }, 1000);
    }


    fetchData() {
        this.triggerModal();
        let that = this;
        let API_URL = URL.local + 'stock/' + this.props.message.ncType;
        let PARAMS = '/1/' + this.state.pagesize + '?date=' + formatDate2(this.state.showDate);
        let REQUEST_URL = API_URL + PARAMS;
        if (!this._isFetching) {
            this._isFetching = true;//用于方式不断的调用
            //这里配置调用后台的url
            Utils.transport(REQUEST_URL, '', function (responseData) {
                if (responseData == -1) {
                    AlertIOS.alert(
                        '您的权限不够',
                        '请您升级权限, 或等到休市之后再来访问.',
                        [
                            {
                                text: '去升级', onPress: () => {
                                if (Key.username == '') {
                                    that.props.navigator.push({
                                        id: 'Register'
                                    })
                                } else {
                                    that.props.navigator.push({
                                        id: 'MyRule'
                                    })
                                }
                            }
                            },
                            {text: '取消'}
                        ]
                    )
                } else if (responseData.length >= 0) {
                    let formData = reformData(responseData);
                    that.setState({
                        dataSource: that.state.dataSource.cloneWithRowsAndSections(formData._dataBlob, formData._sectionID, formData._rowIDs),
                        loaded: 1
                    });
                } else {
                    that.setState({loaded: 2})
                }

                that._isFetching = false;
            })
        }
    }

    _refresh() {
        var TIMES = 1;
        this.state.angle.setValue(0);
        this._anim = Animated.timing(this.state.angle, {
            toValue: 360 * TIMES,
            duration: 800 * TIMES,
            easing: Easing.linear
        }).start(this._animate);
        this.fetchData();
    }

    handleEnd() {
        console.log("Ending!!!");
        this.setState({
            pagesize: this.state.pagesize + 10,
            loadMore: true
        }, function cb() {
            this.fetchData()
        });
    }

    _renderFooter() {
        if (this.state.loadMore) {
            return (
                <View style={styles.footerload}>
                    <ActivityIndicator
                        animating={true}
                        style={{justifyContent:'center'}}
                    />
                    <Text>
                        加载数据...
                    </Text>
                </View>
            )
        }
    }

    _renderHeader() {
        return (
            <View style={styles.th}>
                <Text style={[styles.thText,{flex:4}]}>发布时间</Text>
                <Text style={[styles.thText,{flex:3}]}>股票代码</Text>
                <Text style={[styles.thText,{flex:3}]}>股票名称</Text>
                <Text style={[styles.thText,{flex:2}]}>买点</Text>
                <Text style={[styles.thText,{flex:2}]}>止损</Text>
                <Text style={[styles.thText,{flex:2}]}>止盈</Text>
                <Text style={[styles.thText,{flex:3}]}>持仓时间</Text>
                <Text style={[styles.thText,{flex:2}]}>评级</Text>
            </View>
        );
    }

    _forwardDay() {
        console.log(this.state.showDate.getDate());
        var oldDay = this.state.showDate;
        this.setState({
            showDate: new Date((oldDay / 1000 - 86400) * 1000)
        });
        this.fetchData();
    }

    _backwardDay() {
        console.log(this.state.showDate.getDate());
        var oldDay = this.state.showDate;
        this.setState({
            showDate: new Date((oldDay / 1000 + 86400) * 1000)
        });
        this.fetchData();
    }

    renderNoData() {
        return (
            <View style={styles.container}>
                {
                    this.state.scroll!=''?
                    <ScrollNews content={this.state.scroll}/>:null
                }
                <View style={styles.navbar}>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._forwardDay()}}>
                        <Text style={styles.navText}>前一天</Text>
                    </TouchableHighlight>
                    <View style={{flex:4}}>
                        <Text style={styles.navText}>
                            {formatDate2(this.state.showDate)}
                        </Text>
                    </View>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._backwardDay()}}>
                        <Text style={styles.navText}>后一天</Text>
                    </TouchableHighlight>
                </View>
                <View style={styles.listView}>
                    <Text style={styles.centerText}>
                        暂无数据,请查询其他日期.
                    </Text>
                </View>
            </View>
        );
    }

    renderScene() {
        if (this.state.loaded == 0) {
            return this.renderLoadingView();
        } else if (this.state.loaded == 2) {
            return this.renderNoData();
        }
        return (
            <View style={styles.container}>
                {
                    this.state.scroll!=''?
                    <ScrollNews content={this.state.scroll}/>:null
                }
                <View style={styles.navbar}>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._forwardDay()}}>
                        <Text style={styles.navText}>前一天</Text>
                    </TouchableHighlight>
                    <View style={{flex:4}}>
                        <Text style={styles.navText}>
                            {formatDate2(this.state.showDate)}
                        </Text>
                    </View>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._backwardDay()}}>
                        <Text style={styles.navText}>后一天</Text>
                    </TouchableHighlight>
                </View>

                <ScrollView contentContainerStyle={styles.contentView} horizontal={true} bounces={false}>
                    <ListView
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow.bind(this)}
                        renderSectionHeader={this.renderSectionHeader.bind(this)}
                        renderHeader={this._renderHeader.bind(this)}
                    />
                </ScrollView>
                <Modal visible={this.state.modalVisiable} transparent={true}>
                    <View style={styles.modal}>
                        <Text style={{color:"#ffffff"}}>
                            正在刷新
                        </Text>
                    </View>
                </Modal>
                <TouchableOpacity style={styles.refresh} onPress={this._refresh.bind(this)} underColor="#ffffff">
                    <Animated.View style={{
                        transform: [
                        {rotate: this.state.angle.interpolate({
                          inputRange: [0, 360],
                          outputRange: ['0deg', '360deg']
                        })}]}}>
                        <Icon name="ios-refresh" size={40}
                              style={{height:40,width:40,alignSelf:'center',textAlign:'center'}}
                              color="#ffffff"/>
                    </Animated.View>
                </TouchableOpacity>
            </View>
        );
    }

    renderLoadingView() {
        return (
            <View style={styles.container}>
                {/*<ScrollNews style={styles.scrollNews}
                            marqueeText={this.state.scroll}/>*/}
                <ActivityIndicator
                    animating={true}
                    style={{justifyContent:'center'}}
                />
                <View style={styles.listView}>
                    <Text style={styles.centerText}>
                        正在加载数据，请稍后...
                    </Text>
                </View>
            </View>
        );
    }

    renderSectionHeader(sectionData:string, sectionID:string) {
        return (
            <View key={sectionID} style={styles.section}>
                <Text style={styles.sectiontext}>
                    {sectionData}
                </Text>
            </View>
        );
    }


    renderRow(rowData, sectionID:string, rowID:string) {
        return (
            <View style={styles.Items}>
                <Text style={[styles.mtitle,{flex:4},{color:rowData.color}]}>{rowData.releaseTime}</Text>
                <Text style={[styles.mtitle,{color:rowData.color}]}>{rowData.stockCode}</Text>
                <Text style={[styles.mtitle,{color:rowData.color}]}>{rowData.stockName}</Text>
                <Text style={[styles.title,{color:rowData.color}]}>{rowData.purchasePoint}</Text>
                <Text style={[styles.title,{color:rowData.color}]}>{rowData.stopLoss}</Text>
                <Text style={[styles.title,{color:rowData.color}]}>{rowData.stopProfit}</Text>
                <Text style={[styles.mtitle,{color:rowData.color}]}>{rowData.holdLast}</Text>
                <Text style={[styles.title,{color:rowData.color}]}>{rowData.recommandLevel}</Text>
            </View>
        );
    }

    render() {
        return (
            <Navigator
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                message={this.props.message}
                navigationBar={
                    <Navigator.NavigationBar
                        style={{backgroundColor: '#e02820', alignItems: 'center'}}
                        routeMapper={NavigationBarRouteMapper}/>
                }
            />
        );
    }
}

const styles = StyleSheet.create({
    container: {
        marginTop: 64,
        flex: 1,
        backgroundColor: '#F5FCFF'
    },
    navTitle: {
        color: 'white',
        margin: 10,
        fontSize: 20
    },
    scrollNews: {
        height: 30,
    },
    newstitle: {
        marginTop: 5,
        height: 30,
        width: 200
    },
    refresh:{
        position:'absolute',
        right:10,
        bottom:10,
        width:44,
        height:44,
        justifyContent:'center',
        alignItems:'center',
        borderRadius:5,
        backgroundColor:'rgba(0, 0, 0, 0.5)'
    },
    Items: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 3,
        backgroundColor: '#f5f5f9',
        borderBottomWidth: 0.5,
        borderColor: '#dddddd'
    },
    footerload: {
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row'
    },
    contentView: {
        flex: 12,
        width: 500,
        backgroundColor: '#f5f5f9'
    },
    listView: {
        flex: 12,
        paddingTop: 20,
        backgroundColor: '#f5f5f9',
        justifyContent: 'center',
        alignItems: 'center'
    },
    down: {
        flex: 1,
        backgroundColor: '#000000',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    bottomText: {
        flex: 1,
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 16
    },
    rightContainer: {
        flex: 1,
        height: 70,
        justifyContent: 'flex-start'
    },
    title: {
        flex: 2,
        fontSize: 15,
        textAlign: 'center'
    },
    mtitle: {
        flex: 3,
        fontSize: 14,
        color: '#000000',
        textAlign: 'center'
    },
    thumbnail: {
        width: 100,
        height: 70,
        marginRight: 3,
        resizeMode: Image.resizeMode.stretch
    },
    searchBar: {
        marginTop: 64,
        padding: 3,
        paddingLeft: 8,
        flexDirection: 'row',
        alignItems: 'center'
    },
    searchBarInput: {
        fontSize: 15,
        flex: 1,
        height: 30
    },
    spinner: {
        width: 30
    },
    separator: {
        height: 1,
        backgroundColor: '#eeeeee'
    },
    th: {
        flexDirection: 'row',
        backgroundColor: "#000000",
        height: 30,
        width: 500,
        justifyContent: "center",
        alignItems: 'center'
    },
    thText: {
        flex: 1,
        borderRightWidth: 0.5,
        borderColor: '#dddddd',
        textAlign: 'center',
        fontSize: 13,
        color: '#ffffff'
    },
    navbar: {
        backgroundColor: '#292929',
        flexDirection: 'row',
        alignItems: 'center',
    },
    navbar_side: {
        backgroundColor:"#202020",
        width: 100,
        paddingBottom:5,
        paddingTop:5
    },
    navText: {
        textAlign: 'center',
        fontSize: 18,
        color:"#ffffff"
    },
    centerText: {
        fontSize: 18
    },
    search:{
        flex:1,
        justifyContent:'center',
        paddingRight:10,
        marginRight:10
    },
    modal: {
        position: 'absolute',
        bottom: 50,
        width: 80,
        height: 40,
        borderRadius: 5,
        justifyContent: 'center',
        alignItems: 'center',
        left: Utils.size.width / 2 - 40,
        backgroundColor: '#000000'
    },
    section: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-start',
        padding: 6,
        backgroundColor: '#e02820',
    },
    sectiontext:{
        color:'#ffffff',
        fontSize:17
    }
});
